def setItem(ls, index, val):
   # 长度差1 直接append
   nextIndex = len(ls)
   if nextIndex == index:
      ls.append(val)
   elif nextIndex > index:
      ls[index] = val # 不会越界 直接赋值
   else:
      while nextIndex < index:
         ls.append(None)
         nextIndex += 1
      
      ls.append(val)
   return ls

   
# 列表转换为二维列表
def toGroups(ls, size = 3):
   groups = []
   
   for index, value in enumerate(ls):
      # 商表示位于哪个子列表  余数表明子列表中的索引
      shang, yuShu = divmod(index, size)
      print(shang, yuShu, '<==')
      if len(groups) - 1 < shang:
         setItem(groups, shang, [])

      subGroup = groups[shang]
      if len(subGroup) - 1 < yuShu:
         setItem(subGroup, yuShu, value)

   return groups
   

   
def toGroups2(ls, size = 3):
   appendCount = 0
   groups = []
   newGroup = []
   # enumerate(ls) -> [(0, v0), (1, v1)....]
   for i, v in enumerate(ls):
      if appendCount < size:
         newGroup.append(v)

         appendCount += 1
         
         if appendCount == size or i == len(ls) - 1:
            groups.append(newGroup)
            
            appendCount = 0
            newGroup = []
                  
   return groups


if __name__ == '__main__':


   ls = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
   print(ls)
   print(toGroups2(ls, 4))
   print('-' * 20)
   print(toGroups(ls, 4))



